/*
 * Sapphire
 *
 * Copyright (C) 2018 Florrie Haero
 * Copyright (C) 2018 Alyssa Rosenzweig
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 *
 */

/* Convert a byte array to hex */

function binaryToHex(binary) {
    const u8 = new Uint8Array(binary);
    let str = '';

    for (const v of u8) {
        str += ('00' + v.toString(16)).slice(-2);
    }

    return str;
}


/* SHA-256 hash the password before touching the wire or disk. Encode as per
 * in the backend */

window.hashPassword = function(password) {
    const buffer = new TextEncoder('utf-8').encode(password);
    return crypto.subtle.digest('SHA-256', buffer).then(binaryToHex);
};
